import { Component, OnInit, ViewChild, SimpleChanges } from '@angular/core';
import { ClueDataService } from '../../../../../@core/service/clue-service/clue-data.service';
import { ClueService } from '../../../../../@core/service/typescript-angular-client/api/clue.service';
import {Router,NavigationExtras,ActivatedRoute} from '@angular/router';
import * as moment from 'moment';
import {CaseReviewService} from '../../../../../@core/service/case-review/case-review.service'
import { OrgService } from '../../../../../@core/service/person-select-service/api/org.service';

@Component({
  selector: 'app-editclue',
  templateUrl: './editclue.component.html',
  styleUrls: ['./editclue.component.scss']
})
export class EditclueComponent implements OnInit {

  //区域数据
  public areaData: any;
  //省级联动
  public provinces:any[];
  //市级联动
  public cities:any[];
  //县级联动
  public counties:any[];
  addressDetails: any[]=[];

  public isExpand:boolean = false;
  public dataList:any;
  public sortValue:any;
  public flag:boolean=false;
  public flags:boolean=false;
  public getSelectValue:any = "0";
  public listOfOption = [];
  public  nodes = [];
  public session:any = window.sessionStorage;
  public expandKeys = []; 
  constructor(
    public clueData:ClueDataService,
    public clue:ClueService,
    public router:Router,
    public active:ActivatedRoute,
    public caseReview:CaseReviewService,
    public orgService:OrgService) { 
    this.areaData = clueData.area;
    
  }
  public clueList:any = {};

  public id:any;
  public list:any;
  public myDoc:any;
  public myflag:boolean;
  public v1:any;
  public v2:any;
  public sessionDepart:any = JSON.parse(window.sessionStorage.getItem('organizations'))[0];

  public registerDepartName:any;

  @ViewChild("fullstaff")  fullstaff;
  @ViewChild("select")  select;
  public selectValue:any=[{
    name:"法人",value:"0"
  },{
    name:"个人",value:"1"
  }];
  public clueDocList:any;
  ngOnInit() {
    this.provinces =  this.areaData
    if(!this.session.getItem('areaData')) {
      let id = this.session.getItem('accessToken') || "";
      this.orgService.getAreaById(id).subscribe((data) => {
        if (data['rel'] == true) {
          this.session.setItem('areaData', JSON.stringify(data['data']));
          let  nodesData = data['data'];
          this.nodes = this.DataProcess(nodesData, '0', '机构');
          // 登记机关赋值
          this.v2 = this.sessionDepart.orgId;
          this.v1 = this.sessionDepart.orgParentId;
          this.registerDepartName = this.sessionDepart.orgName
        } else {
          alert(data['message']);
        }
      }, (error) => {
        console.log(error);
      });
    } else {
      let nodesData = JSON.parse(this.session.getItem('areaData'));      
      this.nodes = this.DataProcess(nodesData, '0', '机构');
      for (let j = 0; j < this.nodes.length; j++) {
        this.nodes[j]['children'] = this.DataProcess( nodesData, this.nodes[j]['value'],'机构');
      }
      // 登记机关赋值
        this.v2 = this.sessionDepart.orgId;
        this.v1 = this.sessionDepart.orgParentId;
        this.registerDepartName = this.sessionDepart.orgName
    }


    // getClueById
    const editid = this.active.snapshot.params["id"]
    this.clue.getClueById(editid).subscribe((mySucc:any)=>{
      this.list = mySucc.data;
      if(typeof(this.list.address) == "string"){
        this.list.address= JSON.parse( this.list.address);
      }else{
        this.list.address= this.list.address
      }
      if(typeof(this.list.caseProvider) == "string"){
        this.list.caseProvider= JSON.parse( this.list.caseProvider);
      }else{
        this.list.caseProvider= this.list.caseProvider
      }
      this.id = editid;
      this.sortValue = this.list.clueSource;
      if(this.list.clueDoc){
        this.clueDocList=  JSON.parse(this.list.clueDoc).data
      }



      let province,city,county,detailed;
      //查找返回省级列表
      if(this.list.address.province==this.provinces[0]['key']){
          province =this.list.address.province;
          this.addressDetails[0] = this.provinces[0].label
      }else{
          province = null;
      }


      //查找返回市级列表
      if(this.list.address.city){
        this.cities = this.provinces[0].children;
        city = this.list.address.city;
        this.addressDetails[1] = this.cities.filter(cityF=>cityF.key == city)[0].label

      }else{
        this.cities = [];
        city =null;
      }
      //查找返回县级列表
      if(this.list.address.county){
        this.counties = this.cities.filter(cityItem=>city ==cityItem.key)[0].children;
        county = this.list.address.county;
        this.addressDetails[2] = this.counties.filter(countyF=>county == countyF.key)[0].label

      }else{
        this.counties = [];
        county =null;
      }

      if(this.list.registerDate){
        let datetime = moment(this.list.registerDate).format('YYYY-MM-DD HH:mm:ss')
        this.list.registerDate = datetime
      }else{
        this.list.registerDate = "";
      }

      this.clueList={
        "partyName":this.list.partyName,//当事人名称
        "address" :{
          "province":province,"city":city,"county":county,"detailed":this.list.address.detailed
        },//地址
        phone:this.list.phone,//联系电话
        otherPhone:this.list.otherPhone,//其他联系方式
        clueSource:this.list.clueSource,//线索来源
        clueStatus:"01",	//线索状态
        clueDoc:this.list.clueDoc,
        registerContent:this.list.registerContent,	//案源登记内容
        registerPerson:this.list.registerPerson,//登记人
        registerDepart:this.list.registerDepart,	// 登记机关
        registerNumber:this.list.registerNumber,	// 登记号
        registerDate:this.list.registerDate,//登记时间
        caseProvider:{},//案件提供人
        remarks:this.list.remarks,
        addressDetails:this.list.addressDetails,
        partyPerson:this.session.getItem("realName"),
        partyDepart:this.list.partyDepart,
        registerDepartName:this.list.registerDepartName,
        createUser:this.list.createUser,
        updateUser:this.session.getItem('userId'),
        createTime:this.list.createTime,
        partyPersonId:this.session.getItem('userId')
      };


      this.clueList.clueSource = this.sortValue;

      if(this.sortValue == "1001"){
        this.clueList.caseProvider={
          "jcr1":this.list.caseProvider.jcr1, "ssdw1":this.list.caseProvider.ssdw1,"jcr2":this.list.caseProvider.jcr2,"ssdw2":this.list.caseProvider.ssdw2
        }
      }else if(this.sortValue == "1003"||this.sortValue == "1004" ||this.sortValue == "1005"){
        this.clueList.caseProvider={
          "depname":this.list.caseProvider.depname,"atten":this.list.caseProvider.atten,"telnum":this.list.caseProvider.telnum,"address":this.list.caseProvider.address
        }
      }else if(this.sortValue == "1002"){
        this.getSelectValue = this.list.caseProvider.type;
        if(this.getSelectValue=="0"){
          this.clueList.caseProvider={
            "type":"0",
            "depname": this.list.caseProvider.depname,
            "pic": this.list.caseProvider.pic,
            "telnum": this.list.caseProvider.telnum,
            "address": this.list.caseProvider.address,
            "otherinfo": this.list.caseProvider.otherinfo
            }
        }else if(this.getSelectValue=="1"){
          this.clueList.caseProvider={
            "type":"1","name":this.list.caseProvider.name,"idnum":this.list.caseProvider.idnum,"telnum":this.list.caseProvider.telnum,"address":this.list.caseProvider.address,"otherinfo":this.list.caseProvider.otherinfo
            }
        }
      }
    })  
    // this.orgDefault()//给组织机构赋默认值
  }

   // 将后台返回的数据处理成符合树形结构 
   DataProcess(data, parentId, type) {
    let arrayList = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i]['orgTypeName'] == type && data[i]['officeParentId'] == parentId) {
        let obj = {
          'title': '', 
          'text': '',
          'value': '', 
          'key': '', 
          'parentId': '', 
          'officeCode': '',
          'children': []
        };
        obj.title = data[i]['officeName'] || "";
        obj.text = data[i]['officeName'] || "";
        obj.value = data[i]['officeId'] || "";
        obj.officeCode = data[i]['officeCode'] || "";
        obj.key = data[i]['officeId'] || "";
        obj.parentId = data[i]['officeParentId'] || "";
        obj.children = this.DataProcess(data, obj.value, '机构');
          if (obj.children.length <= 0) {
            obj['isLeaf'] = true;
          }
        arrayList.push(obj);
      }
    }
    return arrayList;
  }
      // 获取树中选中的节点
      getSelectedNodeList(key): void {
        let nodesData = JSON.parse(this.session.getItem('areaData'));
        this.listOfOption = this.DataProcess(nodesData, key, '部门');
        this.registerDepartName = this.select.getSelectedNodeList()[0].origin.title
        this.clueList.registerDepartName = this.registerDepartName
      }

  //省级选择
  onProvinceChange(event){
   if(event!==null){
      this.clueList.address.city = null;
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.cities = this.provinces[0].children;
      this.addressDetails[0] = this.provinces[0].label;
      this.addressDetails[1] = this.addressDetails[2] = "";
    }else{
      this.clueList.address.province = null;
      this.clueList.address.city = null;
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.addressDetails[0] =this.addressDetails[1] = this.addressDetails[2] = "";
      this.cities = [];
      this.counties = [];
    }
  }
  //市级选择
  onCityChange(event){
    if(event!==null){
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      let currCity= this.cities.filter(city=>city.key==event);
      this.counties = currCity[0].children;
      this.addressDetails[1] = currCity[0].label;
      this.addressDetails[2] = "";
    }else{
      this.clueList.address.city = null;
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.addressDetails[1] = this.addressDetails[2] = "";
      this.counties = [];
    }
  }
  //县级选择
  onCountyChange(event){
    if(event!==null){
      let currCounty = this.counties.filter(county=>county.key==event);
      this.addressDetails[2] = currCounty[0].label;
      this.clueList.address.detailed = null;
    }else{
      this.clueList.address.county = null;
      this.clueList.address.detailed = null;
      this.addressDetails[2]='';
    }
  }
  radiochang(e){
    this.getSelectValue = "0";
    if(e == "1001"){
      this.clueList.caseProvider={
        "jcr1":"", "ssdw1":"","jcr2":"","ssdw2":""
      }
    }else if(e == "1003"||this.sortValue == "1004" ||this.sortValue == "1005"){
      this.clueList.caseProvider={
        "depname":"","atten":"","telnum":"","address":""
      }
    }else if(e == "1002"){
      this.clueList.caseProvider={
        "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
      }
     this.onChange(event);
    }
  }
  onChange(event){
    if(event=="0"){
      this.clueList.caseProvider={
        "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
      }
    }else if(event=="1"){
      this.clueList.caseProvider={
        "type":"1","name":"","idnum":"","telnum":"","address":"","otherinfo":""
        }
    }
  }
  onsubmit(callback){  
    
    if(this.clueList.registerDate){
      let datetime = moment(this.clueList.registerDate).format('YYYY-MM-DD HH:mm:ss')
      this.clueList.registerDate = datetime
    }else{
      this.clueList.registerDate = "";
    }
    let  area= this.addressDetails.concat(this.clueList.address.detailed).join('')
    this.clueList.addressDetails = area;
    this.clueList.id=this.id;

    this.clueList.clueSource = this.sortValue;
    this.clueList.clueDoc = this.list.clueDoc;


    // this.clueList.partyDepart = this.session.getItem('userId');

    this.clueList.clueStatus = "02";

    this.clueList.registerDepartName =this.registerDepartName;


    if(this.sortValue == "1001"){
      this.clueList.caseProvider={
        "jcr1":this.clueList.caseProvider.jcr1, "ssdw1":this.clueList.caseProvider.ssdw1,"jcr2":this.clueList.caseProvider.jcr2,"ssdw2":this.clueList.caseProvider.ssdw2
      }
    }else if(this.sortValue == "1003"||this.sortValue == "1004" ||this.sortValue == "1005"){
      this.clueList.caseProvider={
        "depname":this.clueList.caseProvider.depname,"atten":this.clueList.caseProvider.atten,"telnum":this.clueList.caseProvider.telnum,"address":this.clueList.caseProvider.address
      }
    }else if(this.sortValue == "1002"){
      if(this.getSelectValue=="0"){
        this.clueList.caseProvider={
          "type":"0",
          "depname": this.clueList.caseProvider.depname,
          "pic": this.clueList.caseProvider.pic,
          "telnum": this.clueList.caseProvider.telnum,
          "address": this.clueList.caseProvider.address,
          "otherinfo": this.clueList.caseProvider.otherinfo
          }
      }else if(this.getSelectValue=="1"){
        this.clueList.caseProvider={
          "type":"1","name":this.clueList.caseProvider.name,"idnum":this.clueList.caseProvider.idnum,"telnum":this.clueList.caseProvider.telnum,"address":this.clueList.caseProvider.address,"otherinfo":this.clueList.caseProvider.otherinfo
          }
      }
    }

    this.clueList.caseProvider=JSON.stringify(this.clueList.caseProvider);
    this.clueList.address= JSON.stringify(this.clueList.address);
    var list:any = JSON.stringify(this.clueList);
    this.clue.updateClue(list).subscribe((data)=>{ 
      if(data.code==200){
        this.flag=true
        this.flags=false;
        // this.clueData.myAddClue(data)
        if(callback){
          callback()
        }else{
          this.router.navigate(['/main/home/clue/previewdocument/',data.data.id]);
        }
      }else{
        this.flags=true;
        this.clueList.address = JSON.parse( this.clueList.address)
        this.clueList.caseProvider = JSON.parse( this.clueList.caseProvider)
        // window.location.reload()
        // console.log(this.router.url)
      }
    })
  }
  dodoc(e){
    if(e){
      this.myDoc=e;
      this.myflag = true;
    }else{
      this.myflag = false;
    }
  }

  fun(ev){
    this.myflag = ev;
  }

  
  emitFather(){
    this.clueList.clueStatus ='02'
    this.onsubmit(()=>{
      this.router.navigate(['/main/home/clue/cluedetail/',this.clueList.id])
    })
  }
  // 关闭卡片
  closeCard(){
    this.isExpand  = false;
  } 
  // 切换底部card
  cardToggle($event){
    if($event){
      this.isExpand  = $event
    }
  }
}
